<script setup xmlns="">
import { ref , onMounted } from "vue";
import {ElMessage} from "element-plus";
import request from "@/utils/request.js";
import { Edit, Delete } from "@element-plus/icons-vue";


// 数据相关
const users = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(13);
const searchQuery = ref("");

// 搜索用户
const searchUsers = () => {
    currentPage.value = 1; // 搜索时重置到第一页
    loadUsers();
};

// 角色选项映射
const roleOptions = {
  ADMIN: "管理员",
  USER: "普通用户",
  RIDER: "骑手",
};

// 角色筛选相关
const selectedRole = ref(""); // 当前选中的角色

// 角色筛选方法
const filterRole = (value, row) => {
  // 确保筛选逻辑正确匹配
  return row.role === value;
};

// 加载用户数据
const loadUsers = async () => {
  try {
    const res = await request.get("/user/alluser/page", {
      params: {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        username: searchQuery.value,
        nickname: searchQuery.value, // 支持昵称搜索
        email: searchQuery.value,    // 支持邮箱搜索
        role: selectedRole.value || undefined, // 支持角色筛选
      },
    });
    users.value = res.data.list;
    total.value = res.data.total;
  } catch (error) {
    console.error(error);
    ElMessage.error("加载用户数据失败");
  }
};

// 删除用户
const deleteUser = async (username) => {
  ElMessageBox.confirm("确定要删除该用户吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await request.delete(`/user/delete/${username}`);
      ElMessage.success("用户删除成功");
      loadUsers();
    } catch (error) {
      ElMessage.error("删除用户失败");
    }
  });
};

// 编辑用户相关
const editForm = ref({
  username: "",
  password: "",
  role: "",
  nickname: "",
  email: "",
  description: "",
  version: "",
  score: "", // 新增积分字段
});

const editDialogVisible = ref(false);

// 打开编辑对话框
const openEditDialog = (user) => {
  editForm.value = { 
    ...user,
    role: roleOptions[user.role] || user.role, // 转换角色值为中文
    version: user.version,
    password: user.password,
    score: user.score, // 设置积分值
  };
  editDialogVisible.value = true; // 确保正确设置为 true
};

// 添加用户
const addDialogVisible = ref(false);
const addForm = ref({
  username: "",
  password: "",
  role: "",
  nickname: "",
  email: "",
  description: "",
});

// 打开添加用户对话框
const addUser = () => {
  addForm.value = {
    username: "",
    password: "",
    role: "",
    nickname: "",
    email: "",
    description: "",
  };
  addDialogVisible.value = true;
};

// 添加用户表单验证规则
const addRules = {
  username: [{ required: true, message: "账号不能为空", trigger: "blur" }],
  password: [{ required: true, message: "密码不能为空", trigger: "blur" }],
  role: [{ required: true, message: "角色不能为空", trigger: "change" }],
  nickname: [{ required: true, message: "昵称不能为空", trigger: "blur" }],
};

// 编辑用户表单验证规则
const editRules = {
  username: [{ required: true, message: "账号不能为空", trigger: "blur" }],
  role: [{ required: true, message: "角色不能为空", trigger: "change" }],
  nickname: [{ required: true, message: "昵称不能为空", trigger: "blur" }],
};

// 添加用户表单引用
const addFormRef = ref(null);

// 编辑用户表单引用
const editFormRef = ref(null);

// 提交添加用户表单时增加校验逻辑
const submitAdd = async () => {
  addFormRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.error("请检查表单内容");
      return;
    }
    try {
      await request.post("/user/add", addForm.value);
      ElMessage.success("用户添加成功");
      addDialogVisible.value = false;
      loadUsers();
    } catch (error) {
      ElMessage.error("添加用户失败");
    }
  });
};

// 提交编辑用户表单时增加校验逻辑
const submitEdit = async () => {
  editFormRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.error("请检查表单内容");
      return;
    }
    try {
      const roleMapping = Object.entries(roleOptions).reduce((acc, [key, value]) => {
        acc[value] = key;
        return acc;
      }, {});
      const updatedForm = {
        ...editForm.value,
        role: roleMapping[editForm.value.role] || editForm.value.role,
      };
      const log =await request.put("/user/update", updatedForm);
      ElMessage.success("用户信息更新成功");
      editDialogVisible.value = false;
      loadUsers();
    } catch (error) {
      ElMessage.error("更新用户信息失败");
    }
  });
};

// 新增重置搜索方法
const resetSearch = () => {
  searchQuery.value = ""; // 清空搜索框内容
  selectedRole.value = ""; // 清空角色筛选条件
  loadUsers(); // 重新加载用户数据
};

// 当前页码变化时触发
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  loadUsers();
};

// 初始化加载数据
onMounted(() => {
  loadUsers();
});

</script>

<template>
  <div class="user-management-container">
    <!-- 搜索框与添加用户按钮 -->
    <div class="search-container">
      <el-input
          v-model="searchQuery"
          placeholder="请输入账号、昵称或邮箱"
          class="search-input"
          @keyup.enter="searchUsers"
          clearable
      >
        <template #append>
          <el-button type="primary" @click="searchUsers">搜索</el-button>
          <el-button type="primary" @click="resetSearch" style="margin-left: 10px;">重置</el-button>
        </template>
      </el-input>
      <el-button type="primary" @click="addUser" class="add-button">添加用户</el-button>
    </div>

    <!-- 用户表格 -->
    <div class="table-container">
      <el-table :data="users" border class="custom-table">
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="username" label="账号" align="center" />
        <el-table-column prop="role" label="角色" align="center" :filters="[
            { text: '管理员', value: 'ADMIN' },
            { text: '普通用户', value: 'USER' },
            { text: '骑手', value: 'RIDER' }
          ]" :filter-method="filterRole">
          <template #default="scope">
            {{ roleOptions[scope.row.role] || scope.row.role }}
          </template>
        </el-table-column>
        <el-table-column prop="nickname" label="昵称" align="center" />
        <el-table-column prop="email" label="邮箱" align="center" />
        <el-table-column prop="description" label="描述" show-overflow-tooltip align="center" />
        <el-table-column prop="score" label="积分" align="center" />
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button :icon="Edit" size="small" @click="openEditDialog(scope.row)">编辑</el-button>
            <el-button :icon="Delete" size="small" type="danger" @click="deleteUser(scope.row.username)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页器 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="prev, pager, next, jumper, ->, total"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑用户对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑用户" width="30%" class="custom-dialog">
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="80px"
      >
        <el-form-item label="账号">
          <el-input v-model="editForm.username" disabled />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="editForm.password" type="password" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="editForm.role" placeholder="请选择角色">
            <el-option 
              v-for="(label, value) in roleOptions" 
              :key="value" 
              :label="label" 
              :value="label"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="editForm.nickname" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="editForm.email" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="editForm.description" type="textarea" />
        </el-form-item>
        <el-form-item label="积分">
          <el-input v-model="editForm.score" type="number" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加用户对话框 -->
    <el-dialog v-model="addDialogVisible" title="添加用户" width="30%" class="custom-dialog">
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addRules"
        label-width="80px"
      >
        <el-form-item label="账号" prop="username">
          <el-input v-model="addForm.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="addForm.role" placeholder="请选择角色">
            <el-option 
              v-for="(label, value) in roleOptions" 
              :key="value" 
              :label="label" 
              :value="value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="addForm.nickname" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="addForm.email" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="addForm.description" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAdd">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.user-management-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 10px;
}

/* 隐藏滚动条但保持滚动功能 */
:deep(.el-scrollbar__bar) {
  display: none;
}

:deep(.el-scrollbar__wrap) {
  overflow-x: hidden;
}

.search-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.search-input {
  width: 400px;
}

.add-button {
  margin-left: 10px;
}

.table-container {
  margin-bottom: 20px;
}

.custom-table {
  border-radius: 4px;
  overflow: hidden;
}

.custom-table :deep(.el-table__header) {
  background-color: #f5f7fa;
}

.custom-table :deep(.el-table__row) {
  transition: background-color 0.3s;
}

.custom-table :deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.custom-dialog :deep(.el-dialog__header) {
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.custom-dialog :deep(.el-dialog__footer) {
  border-top: 1px solid #ebeef5;
  padding-top: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>